package com.example.shw.twocache

import android.content.Context
import android.graphics.*
import android.view.MotionEvent
import android.view.View

class DrawViewTwo (context: Context, width: Int, height: Int) : View(context){
    private var preX = 0f
    private var preY = 0f
    private val path = Path()
    internal var paint = Paint(Paint.DITHER_FLAG)

    private var cacheBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)

    private var cacheCanvas = Canvas()
    private val bmpPaint = Paint()

    init {
        cacheCanvas.setBitmap(cacheBitmap)

        paint.color = Color.RED

        paint.style = Paint.Style.STROKE
        paint.strokeWidth = 1f

        paint.isAntiAlias = true
        paint.isDither = true
    }

    override fun onTouchEvent(event: MotionEvent): Boolean {
        val x = event.x
        val y = event.y
        when (event.action)
        {
            MotionEvent.ACTION_DOWN -> {
                path.moveTo(x, y)
                preX = x
                preY = y
            }
            MotionEvent.ACTION_MOVE -> {
                path.lineTo(x, y)
                preX = x
                preY = y
            }
            MotionEvent.ACTION_UP -> {
                cacheCanvas.drawPath(path, paint)
                path.reset()
            }
        }
        invalidate()
        return true
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        canvas.drawBitmap(cacheBitmap, 0f, 0f, bmpPaint)
        canvas.drawPath(path, paint)
    }
}